package com.xtc.netty.tomcat.http;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;

public class MyResponse {

    private ChannelHandlerContext ctx;
    private HttpRequest req;

    public MyResponse(ChannelHandlerContext ctx, HttpRequest req) {
        this.ctx = ctx;
        this.req = req;
    }

    public void write(String msg) throws Exception {
        try {
            if (msg == null || "" == msg) {
                return;
            }

            // 设置Http协议及请求头信息
            FullHttpResponse response = new DefaultFullHttpResponse(
                    // 设置Http的版本为1.1
                    HttpVersion.HTTP_1_1,
                    // 设置响应状态码
                    HttpResponseStatus.OK,
                    // 将输出值写出，编码为UTF-8
                    Unpooled.wrappedBuffer(msg.getBytes("UTF-8")));

            response.headers().set("Content-Type", "text/html;");

            ctx.write(response);
        } finally {
            ctx.flush();
            ctx.close();
        }
    }
}
